package com.huanxing.cloud.mall.api.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huanxing.cloud.common.core.constant.CommonConstants;
import com.huanxing.cloud.mall.api.mapper.OrderItemMapper;
import com.huanxing.cloud.mall.api.mapper.OrderRefundMapper;
import com.huanxing.cloud.mall.api.service.IOrderRefundService;
import com.huanxing.cloud.mall.common.entity.OrderItem;
import com.huanxing.cloud.mall.common.entity.OrderRefund;
import com.huanxing.cloud.mall.common.enums.OrderItemEnum;
import com.huanxing.cloud.mall.common.enums.OrderRefundEnum;
import com.huanxing.cloud.security.handler.HxBusinessException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商城退款单
 *
 * @author lijx
 * @date 2022/5/31
 */
@Service
@AllArgsConstructor
public class OrderRefundServiceImpl extends ServiceImpl<OrderRefundMapper, OrderRefund> implements IOrderRefundService {

	private final OrderItemMapper orderItemMapper;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public OrderRefund saveRefund(OrderRefund orderRefund) {
		OrderItem orderItem = orderItemMapper.selectById(orderRefund.getOrderItemId());
		if (ObjectUtil.isNull(orderItem)) {
			throw new HxBusinessException("子订单不存在");
		}
		// 只有正常订单可申请退款
		if (OrderItemEnum.STATUS_0.getCode().equals(orderItem.getStatus())) {
			if (OrderRefundEnum.STATUS_1.getCode().equals(orderRefund.getStatus())) {
				orderItem.setStatus(OrderItemEnum.STATUS_1.getCode());
			}
			else if (OrderRefundEnum.STATUS_2.getCode().equals(orderRefund.getStatus())) {
				orderItem.setStatus(OrderItemEnum.STATUS_2.getCode());
			}
			else {
				throw new HxBusinessException("退款状态错误");
			}
			orderRefund.setRefundAmount(orderItem.getPaymentPrice());
			orderRefund.setArrivalStatus(CommonConstants.NO);
			orderRefund.setOrderId(orderItem.getOrderId());
			baseMapper.insert(orderRefund);
			orderItemMapper.updateById(orderItem);
		}
		return orderRefund;
	}

	@Override
	public IPage<OrderRefund> getPage(Page page, OrderRefund orderRefund) {
		return baseMapper.selectPage(page, orderRefund);
	}

	@Override
	public OrderRefund getRefundById(String id) {
		return baseMapper.selectRefundById(id);
	}

}
